package com.xiaohong.jwt.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;

/**
 * @author : xiaohong
 * @date : 2021/4/30 11:22
 */
@Configuration
@EnableWebSecurity
public class UserService implements UserDetailsService {

    @Autowired
    private PasswordEncoder passwordEncoder;


    /**
     * 自定义登录逻辑
     * @param s
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        System.out.println("执行了loadUserByUsername方法");
        // 查询数据库判断用户是否存在
        if (!s.equals("xiaohong")){
            throw new RuntimeException("用户不存在！");
        }
        // 获取密码（注册时已经加密加密以后的）进行解析
        String password = passwordEncoder.encode("123");
        // 设置权限 设置角色时前缀默认时ROLE_
        return new User(s,password, AuthorityUtils.
                commaSeparatedStringToAuthorityList("admin,normal,ROLE_xiaohong," +
                        "/test.html,/insert,/delete"));
    }



}
